package com.molyfun.parents.activity.common;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.hyphenate.util.PathUtil;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.activity.record.MediaRecorderActivity;
import com.molyfun.parents.fragment.dialog.CommonChooseDialogFragment;
import com.molyfun.parents.impl.IPicUploadCallback;
import com.molyfun.parents.rest.QiniuSDK;
import com.molyfun.parents.rest.bean.RecordResponse;
import com.molyfun.parents.utils.BitmapHelp;
import com.molyfun.parents.utils.BitmapUtil;
import com.molyfun.parents.utils.FileUtils;
import com.molyfun.parents.utils.Tools;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.model.MediaRecorderConfig;

//import static com.molyfun.parents.activity.record.MainTabRecordFragment.FLAG_VIDEO_REQUEST_CODE;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/25/16.
 */
public abstract class BaseChoosePicActivity extends BaseActivity implements IPicUploadCallback {

    private Uri mCameraImageUri, mImageUri;

    private final static int SELECT_PIC_KITKAT = 3;
    private final static int SELECT_PIC = 4;
    private final static int REQ_CODE_CAMERA = 5;
    private final static int SELECT_VIDEO = 6;

    private final static int FLAG_GET_PIC_DELAY_MSG = 1001;

    private final static int FLAG_GET_PIC_DELAY_SECOND = 1000;
    private final static int FLAG_VIDEO_REQUEST_CODE = 1010;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();

    }

    private void initData() {
        File galleryFile = new File(MFPApplication.cacheDir + "/" + "icon"
                + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
        mImageUri = Uri.fromFile(galleryFile);

        File cameraFile = new File(MFPApplication.cameraDir, new SimpleDateFormat("yyyyMMdd-HHmmss")
                .format(new Date()) + ".jpg");
        mCameraImageUri = Uri.fromFile(cameraFile);
    }

    private Handler mPicProcessHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FLAG_GET_PIC_DELAY_MSG:
                    readLocalImage(mCameraImageUri);
                    break;
            }
        }
    };

    public void choosePic() {
        if (FileUtils.isSDCardMounted()) {
            showOptionsDialog();
        } else {
            toast("没有安装SD卡!");
        }
    }

    public void chooseMedia() {
        if (FileUtils.isSDCardMounted()) {
            showMediaOptionsDialog();
            initVideoConfig();
        } else {
            toast("没有安装SD卡!");
        }
    }

    private void initVideoConfig() {
        VCamera.setVideoCachePath(FileUtils.VIDEOPATH);
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK，必须
        VCamera.initialize(BaseChoosePicActivity.this);
    }


    // 选择图片来源
    private void showOptionsDialog() {
        String[] items = new String[]{"拍照", "选择本地图片"};

        DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0://拍照
                        takePicture();
                        break;
                    case 1://选择本地图片
                        choosePicture();
                        break;
                }
            }
        };

        new AlertDialog.Builder(this).setItems(items,
                click).show();
    }

    // 选择图片来源
    private void showMediaOptionsDialog() {
        String[] items = new String[]{"拍照", "选择本地图片", "拍摄视频"};//, "选择本地视频"};

        DialogInterface.OnClickListener click = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0://拍照
                        takePicture();
                        break;
                    case 1://选择本地图片
                        choosePicture();
                        break;
                    case 2://排视频
                        recordVideo();
                        break;
//                    case 3://选择本地图片
//                        chooseVideo();
//                        break;
                }
            }
        };

        new AlertDialog.Builder(this).setItems(items,
                click).show();
    }

    public void recordVideo() {
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .doH264Compress(true)
                .smallVideoWidth(480)
                .smallVideoHeight(480)
                .recordTimeMax(60 * 1000)
                .maxFrameRate(20)
                .minFrameRate(8)
                .captureThumbnailsTime(1)
                .recordTimeMin((int) (1.5 * 1000))
                .build();

        startActivityForResult(new Intent(BaseChoosePicActivity.this, MediaRecorderActivity.class).putExtra(MediaRecorderActivity.MEDIA_RECORDER_CONFIG_KEY, config), FLAG_VIDEO_REQUEST_CODE);
//        MediaRecorderActivity.goSmallVideoRecorder(getActivity(), config, FLAG_VIDEO_REQUEST_CODE);
    }


    public void takePicture() {
        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.ACTION_IMAGE_CAPTURE_SECURE");
        camera.putExtra("output", mCameraImageUri);
        startActivityForResult(camera, REQ_CODE_CAMERA);
    }

    /**
     * 只选择照片上传，用于record菜单
     */
    public void choosePicture() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/jpeg");
            startActivityForResult(intent, SELECT_PIC_KITKAT);
        } else {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, SELECT_PIC);
        }
    }

    protected void onVideoUploadBegin(String videoPath, String cover){

    }

    /**
     * 只选择照片上传，用于record菜单
     */
    public void chooseVideo() {
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_VIDEO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {


            case SELECT_PIC_KITKAT:
                // 从相册返回
                if (resultCode == RESULT_OK && data != null) {
                    Uri localUri = data.getData();
                    if (localUri == null) {
                        return;
                    }
                    String path = BitmapHelp.getPath(this, localUri);
                    if (!TextUtils.isEmpty(path)) {
                        Uri uri = Uri.fromFile(new File(path));
                        readLocalImage(uri);
                    }
                }

                break;
            case SELECT_PIC:
                // 从相册返回
                if (resultCode == RESULT_OK && data != null) {
                    Uri mUri = data.getData();
                    if (mUri == null) {
                        return;
                    }
                    readLocalImage(mUri);
                }
                break;

            case SELECT_VIDEO:
                if (resultCode == RESULT_OK && data != null) {
                    Uri mUri = data.getData();
                    if (mUri == null) {
                        return;
                    }
                    String aPath = Tools.getFilePath(this, mUri);

                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(aPath, 3);
                        ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.close();
                        onVideoUploadBegin(aPath, file.getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    sendVideo2Server(getRealFilePath(BaseChoosePicActivity.this, mUri));
                }
                break;
            case REQ_CODE_CAMERA:
                if (resultCode == RESULT_OK) {
                    // 从相机返回,从设置相机图片的输出路径中提取数据
//                    readLocalImage(mCameraImageUri);
                    mPicProcessHandler.sendEmptyMessageDelayed(FLAG_GET_PIC_DELAY_MSG, FLAG_GET_PIC_DELAY_SECOND);
                }

                break;
            case FLAG_VIDEO_REQUEST_CODE:
                if(data != null){
                    final String path = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if(!mUploadPathLast.equals(path)){
                        mUploadPathLast = path;
                        new CommonChooseDialogFragment.CommonChooseDialogBuilder("放弃", "确定", "是否使用该视频?")
                                .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                                    @Override
                                    public void onConfirm() {
                                        sendVideo2Server(path);
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                })
                                .build(getSupportFragmentManager().beginTransaction());
                    }

                }

                break;
            default:
                break;
        }
    }

    private String mUploadPathLast = "";
    /**
     * 容错，防止多次调用
     */
    private String mLastUploadVideoPath;

    protected void sendVideo2Server(final String videoPath) {
        if(!TextUtils.isEmpty(mLastUploadVideoPath)){
            if(mLastUploadVideoPath.equals(videoPath)){
                return;
            }
        }
        mLastUploadVideoPath = videoPath;
        showProgressDialog();
        //添加到列表，上传到服务器,列表loading
        MFPApplication.getInstance().getQiniuSDK().uploadFile(videoPath, "mfp/" + getAttachmentFolder()  + "/video_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".mp4"
                , new QiniuSDK.OnFileUpLoadCallback() {
                    @Override
                    public void onFileUpload(String videoUrl) {
                        //发送到自己服务器
                        dismissProgressDialog();
                        onVideoUploadSuccess("", videoUrl);
//                        onVideoUploadSuccess(videoUrl + "?vframe/png/offset/0/w/480/h/480", videoUrl);
                    }

                    @Override
                    public void onFileUploadFailed(String path, String UploadPath) {
                        onVideoUploadFailed(path, UploadPath);
                    }
                });

    }

    protected void onVideoUploadFailed(String path, String UploadPath){
        onVideoUploadSuccess(path, UploadPath);
    }

    /**
     * 图片重新上传占位记录
     * @param placeHolderRecordBean
     */
    public void sendPlaceHolderRecord(final RecordResponse.PlaceHolderRecordBean placeHolderRecordBean){
        showProgressDialog();
        //添加到列表，上传到服务器,列表loading
        MFPApplication.getInstance().getQiniuSDK().uploadFile(placeHolderRecordBean.getPath(), placeHolderRecordBean.getUploadPath()
                , new QiniuSDK.OnFileUpLoadCallback() {
                    @Override
                    public void onFileUpload(String url) {
                        //发送到自己服务器
                        dismissProgressDialog();
                        onPictureUploadSuccess(placeHolderRecordBean.getPath(), url + QiniuSDK.QINIU_URL_AVATAR_POSTFIX, url);
                    }

                    @Override
                    public void onFileUploadFailed(String path, String UploadPath) {

                    }
                });
    }

    private void readLocalImage(Uri uri) {
        if (uri != null) {
//            startPhotoCrop(uri, REQ_CODE_PHOTO_CROP); // 图片裁剪

            try {
                BitmapUtil.compressBitmap(getRealFilePath(BaseChoosePicActivity.this, uri), mImageUri.getPath());
//                BitmapUtil.compressBitmap(uri.getPath(), mImageUri.getPath());
                showProgressDialog();
                final String uploadPath = getAttachmentFolder() + "/ic_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".jpg";
                onPictureUploadBegin(Tools.getFilePath(BaseChoosePicActivity.this, mImageUri), uploadPath);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final String localPath = Tools.getFilePath(BaseChoosePicActivity.this, mImageUri);
                        MFPApplication.getInstance().getQiniuSDK().uploadFile(localPath, uploadPath
                                , new QiniuSDK.OnFileUpLoadCallback() {
                                    @Override
                                    public void onFileUpload(String url) {
                                        dismissProgressDialog();
                                        onPictureUploadSuccess(localPath, url + QiniuSDK.QINIU_URL_AVATAR_POSTFIX, url);
                                    }

                                    @Override
                                    public void onFileUploadFailed(String path, String UploadPath) {
                                        onPictureUploadFailed(path, UploadPath);
                                    }
                                });
                    }
                }).run();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //刷新本地压缩缓存地址
        File galleryFile = new File(MFPApplication.cacheDir + "/" + "icon"
                + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
        mImageUri = Uri.fromFile(galleryFile);
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


}
